<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\footprint\Article;
use app\admin\model\footprint\ExamineUser;
use app\api\model\FootprintArticleModel;
use app\common\controller\Api;

class Footprint extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'/*, 'articleList', 'articleInfo'*/];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 我的发布
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mine()
    {
        date_default_timezone_set('PRC');
        $limit = input('limit') ?? 15;

        $time = [];
        if (input('time')) {
            $time = [
                strtotime(input('time') . '-01-01 00:00:00'),
                strtotime(input('time') . '-12-31 23:59:59')
            ];
        }

        // 查询自己是不是拥有审核权限
        $examine = ExamineUser::where(['user_id' => $this->auth->id])->find();

        $params['a.status'] = input('status');
        $params['a.user_id'] = $this->auth->id;

        if ((bool)$examine == true && $params['a.status'] == 0) {
            unset($params['a.user_id']);
        }

        $list = FootprintArticleModel::getList($params, $time, $limit);

        $this->success('成功', [
            'list' => $list,
            'is_examine' => $examine ? true: false
        ]);
    }

    /**
     * 发布文章
     */
    public function sendArticle()
    {
        $title = input('title') ?? null;
        $content = input('content') ?? null;
        $status = input('status') ?? 0;
        $diagram = input('diagram/a') ?? null;

        if (!$title || !$content) {
            $this->error(__('Invalid parameters'));
        }

        // 审核状态 0待审核 1草稿 2审核成功 3审核拒绝
        if ($status != 0 && $status != 1) {
            $this->error(__('Invalid parameters'));
        }
        if (empty($this->auth->id)){
            $this->error(__('请先登录'));
        }

        $params = [
            'title' => $title,
            'content' => $content,
            'status' => $status,
            //'diagram' => htmlspecialchars_decode($diagram),
            'user_id' => $this->auth->id
        ];

        // 从上传的文件中拆分视频和图片
        if ($diagram) {
            $picSuffix = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
            $videoSuffix = ['mp4','avi','mpeg','wmv','mov','flv','avchd','webm','wkv'];
            $pics = [];
            $video = '';
            //$diagrams = json_decode($params['diagram'], true);
            $diagrams = $diagram;
            //trace($params,'debug');
            trace($diagrams,'debug');
            foreach ($diagrams as $diagram) {
                $suffix = pathinfo($diagram, PATHINFO_EXTENSION);
                if (in_array($suffix, $picSuffix)) {
                    $pics[] = $diagram;
                } elseif(in_array($suffix, $videoSuffix)) {
                    $video = $diagram;
                }
            }
            $params['diagram'] = json_encode($pics);
            $params['video'] = $video;
        }

        // 获取视频第一帧图片
        if (!empty($params['video'])) {
            $fileName = "/uploads/" . md5(microtime() . mt_rand(0, 99999)) . ".png";
            $v = str_replace('https://', 'http://', $params['video']);
            $shell = "/usr/local/ffmpeg/bin/ffmpeg -i " . $v . " -ss 1 -y -frames:v 1 -q:v 1 ." . $fileName . " 2>&1";
            trace($shell,'debug');
            exec($shell, $output, $resCode);
            if ($resCode != 0) {
                $this->error('生成视频封面图失败，请联系管理员');
            }

            $params['video_first'] = $fileName;
        }

        $res = FootprintArticleModel::create($params, true);
        if ($res) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }

    /**
     * 编辑文章
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editArticle()
    {
        $articleId = input('article_id', null);
        if (!$articleId) {
            $this->error(__('Invalid parameters'));
        }


        $info = FootprintArticleModel::where([
            'id' => $articleId,
        ])->find();
        if (!$info)
            $this->error(__('No results were found'), null, 404);

        $title = input('title') ?? null;
        $content = input('content') ?? null;
        $status = input('status') ?? 0;
        $diagram = htmlspecialchars_decode(input('diagram')) ?? null;

        if (!$title || !$content) {
            $this->error(__('Invalid parameters'));
        }

        // 审核状态 0待审核 1草稿 2审核成功 3审核拒绝
        if ($status != 0 && $status != 1) {
            $this->error(__('Invalid parameters'));
        }

        // 从上传的文件中拆分视频和图片
        if ($diagram) {
            $picSuffix = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
            $videoSuffix = ['mp4','avi','mpeg','wmv','mov','flv','avchd','webm','wkv'];
            $pics = [];
            $video = '';
            if (!is_array($diagram)){
                $diagrams = json_decode($diagram, true);
            }else{
                $diagrams = $diagram;
            }

            foreach ($diagrams as $diagram) {
                $suffix = pathinfo($diagram, PATHINFO_EXTENSION);
                if (in_array($suffix, $picSuffix)) {
                    $pics[] = $diagram;
                } elseif(in_array($suffix, $videoSuffix)) {
                    $video = $diagram;
                }
            }

            $info->diagram = json_encode($pics);
            $info->video = $video;
        }

        $info->video_first = null;
        // 获取视频第一帧图片
        if (!empty($info->video)) {
            $fileName = "/uploads/" . md5(microtime() . mt_rand(0, 99999)) . ".png";

            $v = str_replace('https://', 'http://', $info->video);
            $shell = "/usr/local/ffmpeg/bin/ffmpeg -i " . $v . " -ss 1 -y -frames:v 1 -q:v 1 ." . $fileName . " 2>&1";
            exec($shell, $output, $resCode);

            if ($resCode != 0) {
                $this->error('生成视频封面图失败，请联系管理员');
            }

            $info->video_first = $fileName;
        }

        $info->title = $title;
        $info->content = $content;
        $info->status = $status;

        if ($info->save()) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }

    /**
     * 删除文章
     */
    public function delArticle()
    {
        $id = input('article_id') ?? null;
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }

        if (FootprintArticleModel::destroy(['id' => $id])) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }

    /**
     * 文章列表
     */
    public function articleList()
    {
        $limit = input('limit') ?? 15;
        $user = $this->auth->getUser();
        $params = [
            'a.status' => '2'
        ];

        $list = FootprintArticleModel::getList($params, null, $limit);
        $list['is_qing'] = $user['is_qing'];
        $this->success('成功', $list);
    }

    /**
     * 文章详情
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function articleInfo()
    {
        $articleId = input('article_id') ?? null;
        $info = FootprintArticleModel::where([
            'id' => $articleId,
        ])->find();
        if (!$info)
            $this->error(__('No results were found'), null, 404);

        if ($info->user_id == $this->auth->id) {
            $info->is_reading = 1;
            $info->save();
        }

        $avatar = '';
        $nickname = '';

        if ($info->admin_user_id > 0) { // 后台用户发布文章
            $userInfo = Admin::where('id', $info->admin_user_id)->find();
            $avatar = $userInfo->avatar;
            $nickname = $userInfo->nickname;
        }

        if ($info->user_id > 0) { // 前台用户发布文章
            $userInfo = \app\admin\model\User::where('id', $info->user_id)->find();
            $avatar = $userInfo?$userInfo->avatar:'';
            $nickname = $userInfo?$userInfo->nickname:'';
        }

        $examine = ExamineUser::where(['user_id' => $this->auth->id])->find();

        $info->examine = (bool)$examine;

        $info->avatar = $avatar;
        $info->nickname = $nickname;
        $this->success(__('Operation completed'), $info);
    }

    /**
     * 审核文章
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function examine()
    {
        // 查询自己是不是拥有审核权限
        $examine = ExamineUser::where(['user_id' => $this->auth->id])->find();

        if (!$examine)
            $this->error('您没有审核权限~');

        $article = Article::get(input('article_id', null));
        $status = input('status', null);
        $examineDesc = input('examineDesc', null);
        if (!$article || !$status)
            $this->error(__('Invalid parameters'));

        if ($status < 2) {
            $this->error(__('Invalid parameters'));
        }

        if ($article->status > 1)
            $this->error('该文章已审核');

        if ($status == 3 && !$examineDesc)
            $this->error('请填写拒绝原因！');

        if ($status == 2)
            $examineDesc = null;

        $article->status = input('status');
        $article->examine = $examineDesc;
        if (!$article->save())
            $this->error(__('Operation failed'));

        $this->success('审核成功！');
    }
}
